<template>
  <div>
    <nav-bar :title="title" :isShow="false"></nav-bar>
    <form action="/">
      <van-row type="flex" justify="space-between" align="center">
        <van-col span="20">
          <van-field
            style="padding-left: 23px"
            left-icon="calendar-o"
            clickable
            readonly
            name="calendar"
            :value="range_date"
            placeholder="点击选择日期"
            @click="showCalendar = true"
            clearable
          />
        </van-col>
        <van-col span="4">
          <van-button
            icon="bill-o"
            type="primary"
            size="mini"
            @click.prevent="handleBalance"
          >
            结 算
          </van-button>
        </van-col>
      </van-row>
    </form>
    <van-calendar
      type="range"
      v-model="showCalendar"
      :min-date="minDate"
      @confirm="onConfirm"
    />
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell title="商家品鉴卡核销记录">
        <template>
          合计：<van-tag round type="success">{{ counts }}</van-tag>
        </template>
      </van-cell>
      <van-cell-group>
        <van-cell
          icon="passed"
          v-for="item in records"
          :key="item.id"
          :title="item.card_name"
        >
        <template>
          <van-tag round type="success">{{ item.flag_name }}</van-tag>
        </template>
          <template #label>
            <div>{{ item.retailer_name }}</div>
            <div>{{ item.name }}</div>
            <div>{{ item.confirm_time }}</div>
          </template>
        </van-cell>
      </van-cell-group>
    </van-list>
    <!-- 弹出窗口 -->
    <van-dialog
      v-model="show"
      title="商家结算"
      show-cancel-button
      @confirm="onConfirmBalance"
      :before-close="onBeforeClose"
    >
      <van-field
        readonly
        clickable
        name="balance_date"
        :value="balance_date"
        colon
        label="结算时间"
        placeholder="点击选择日期"
        @click="showCalendar1 = true"
      />
    </van-dialog>

    <van-calendar
      v-model="showCalendar1"
      :min-date="minDate"
      @confirm="onConfirm1"
    />
  </div>
</template>

<script>
// import { mapGetters } from "vuex";
import NavBar from "@/components/NavBar";
import { getWxClientSampleRecords, wxBalanceBill } from "@/api/card";
import { formatDateTime } from "@/utils/datetime";

export default {
  name: "BalanceAccountList",

  props: ["retailer_id"],

  components: {
    NavBar,
  },

  computed: {
    minDate() {
      let datetime = new Date();
      datetime = datetime.setFullYear(datetime.getFullYear() - 2);
      return new Date(datetime);
    },
  },

  data() {
    return {
      title: this.$route.meta.title,

      records: [],
      loading: false,
      finished: false,

      balance_date: null,

      listQuery: {
        page: 1,
        page_size: 10,
        flag: 2,
        retailer_id: this.retailer_id,
        begin_date: null,
        end_date: null,
      },
      counts: 0,

      show: false,
      showCalendar: false,
      showCalendar1: false,
      range_date: null,
    };
  },

  methods: {
    onLoad() {
      this.getSampleRecords();
    },

    getSampleRecords() {
      this.loading = true;
      this.counts = 0;
      getWxClientSampleRecords(this.listQuery)
        .then((res) => {
          this.counts = res.data.count;
          if (res.data.results.length === 0) {
            this.records = []; // 清空数组
            this.finished = true; // 停止加载
          }
          this.listQuery.page = res.data.page;
          this.records.push(...res.data.results);
          this.loading = false;

          if (this.records.length >= res.data.count) {
            this.finished = true; // 结束加载状态
          }
        })
        .catch(() => {
          this.loading = false;
          this.finished = true;
          this.$toast("获取数据失败！");
        });
    },

    handleBalance() {
      this.balance_date = null;
      this.show = true;
    },

    onConfirm1(date) {
      this.showCalendar1 = false;
      this.balance_date = formatDateTime(date, "YYYY-MM-DD");
    },

    onBeforeClose(action, done) {
      if (action === "confirm") {
        if (this.balance_date == null || this.balance_date.length === 0) {
          this.$toast("请选择结算时间");
          done(false);
        } else {
          this.show = false;
          done(true);
        }
      } else {
        this.show = false;
        done(true);
      }
    },

    onConfirmBalance() {
      console.log("balance");

      if (this.balance_date == null || this.balance_date.length === 0) return;

      const data = {
        balance_date: this.balance_date,
        retailer_id: this.retailer_id,
      };
      console.log(data);
      wxBalanceBill(data)
        .then((res) => {
          this.$toast.success(res.data.message);
          this.records = [];
          this.onLoad();
        })
        .catch((error) => {
          this.$toast.success(error.response.data.message);
        });
    },

    onConfirm(date) {
      const [start, end] = date;
      this.showCalendar = false;
      const begin_date = formatDateTime(start, "YYYY-MM-DD");
      const end_date = formatDateTime(end, "YYYY-MM-DD");
      this.listQuery.begin_date = begin_date;
      this.listQuery.end_date = end_date;
      this.range_date = `${begin_date} / ${end_date}`;
      this.records = [];
      this.counts = 0;
      this.listQuery.page = 1;
      this.onLoad();
    },
  },
};
</script>

<style  scoped>
.van-field__label {
  color: black;
}
</style>